<template>
  <div class="add-move-storage">
    <el-card>
      <div class="form-header">
        <div class="form-title">新增移库单</div>
        <div class="required-tip">*为必填项</div>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="移库单号">
              <el-input
                v-model="form.movingCode"
                placeholder="可不填写,自动生成"
                :readonly="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="移库单类型" prop="allotWarehouseType">
              <el-select
                v-model="form.allotWarehouseType"
                placeholder="请选择移库类型"
              >
                <el-option label="移库上架" value="移库上架" />
                <el-option label="仓库移库" value="仓库移库" />
                <el-option label="报损移库" value="报损移库" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input v-model="form.orderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input :value="form.createUseName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-input :value="form.createTime" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.notes"
                type="textarea"
                :rows="2"
                maxlength="300"
                show-word-limit
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px">
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span class="form-title">产品信息</span>
          <el-button type="primary" @click="fetchProductOptions"
            >+ 新增产品</el-button
          >
        </div>
      </template>
      <el-table :data="productList" border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="batch" label="批次" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="allotCount" label="数量">
          <template #default="scope">
            <el-input v-model="scope.row.allotCount" placeholder="输入数量" />
          </template>
        </el-table-column>
        <el-table-column prop="currentLocation" label="当前库位">
          <template #default="scope">
            <span>{{ scope.row.currentLocation }}</span>
          </template>
        </el-table-column>
        <el-table-column label="移入库位" width="300">
          <template #default="scope">
            <div style="display: flex; gap: 8px">
              <el-select
                v-model="scope.row.original_Position"
                placeholder="选择仓库"
                style="width: 120px"
                @change="(value: number) => handleWarehouseChange(value, scope.$index)"
              >
                <el-option
                  v-for="warehouse in warehouseOptions"
                  :key="warehouse.id"
                  :label="warehouse.warehouse_Name"
                  :value="warehouse.id"
                />
              </el-select>
              <el-select
                v-model="scope.row.new_StorageId"
                placeholder="选择库位"
                style="width: 120px"
                :disabled="!scope.row.original_Position"
              >
                <el-option
                  v-for="storage in scope.row.storageOptions"
                  :key="storage.id"
                  :label="storage.storage_Name"
                  :value="storage.id"
                />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="text" @click="removeProduct(scope.$index)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div style="text-align: center; margin-top: 30px">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="showProductDialog" title="选择产品" width="80%">
      <!-- 查询区域 -->
      <div style="margin-bottom: 10px; display: flex; align-items: center">
        <el-input
          v-model="searchForm.product_Number"
          placeholder="请输入编码"
          style="width: 180px; margin-right: 10px"
        />
        <el-input
          v-model="searchForm.product_Name"
          placeholder="请输入名称"
          style="width: 180px; margin-right: 10px"
        />
        <el-button type="primary" @click="fetchProductOptions">搜索</el-button>
      </div>
      <!-- 商品表格 -->
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="product_Number" label="产品编码" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="category_Name" label="类别" />
        <el-table-column prop="storage_Unit" label="存储单位" />
        <el-table-column prop="packaging_Type" label="包装类型" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="weight" label="重量" />
      </el-table>
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery1.totalCount"
            >
              共{{ pageQuery1.totalCount }}条 每页显示{{
                pageQuery1.pagesize
              }}条 当前第{{ pageQuery1.pageindex }}页/共{{
                pageQuery1.totalPage
              }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery1.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery1.pageindex == 1"
                @click="pageQuery1.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery1.totalCount"
            >
              <el-button
                :disabled="pageQuery1.pageindex == pageQuery1.totalPage"
                @click="pageQuery1.pageindex = pageQuery1.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="showProductDialog = false">关闭</el-button>
        <el-button type="primary" @click="onSelectProducts">选择</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Delete } from "@element-plus/icons-vue";

import type { ComponentSize } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
const size = ref<ComponentSize>("default");
import axios from "axios";
import { StorageRed, StorageWrite } from "@/http/axiosHelper";
  import { ElMessage } from "element-plus";

  // import { StorageRed } from "@/http/axiosHelper";
// import { StorageWrite } from "@/http/axiosHelper";

const router = useRouter();
const form: any = reactive({
  tableType: 0,
  movingCode: "",
  allotWarehouseType: "",
  allotCount: 0,
  orderCode: "",
  original_Warehouse: "",
  original_StorageId: "",
  original_Position: "",
  new_StorageId: "",
  reviewer: "",
  reason: "",
  notes: "",
  state: "",
  batch: "",
  createUse: Number(localStorage.getItem("id")) || 0, // 用户ID（数字）
  createUseName: localStorage.getItem("userName") || "", // 用户姓名（显示用）
  createTime: new Date().toISOString().split("T")[0],
});

interface ProductItem {
  id: Number;
  product_Id: Number;
  product_Number: string;
  product_Name: string;
  specifications: string;
  category_ID: Number;
  category_Name: string;
  batch: string;
  storage_Unit: string;
  packaging_Type: string;
  price: string;
  weight: Number;
  allotCount: Number;
  warehouse_ID: Number;
  storage_ID: Number;
  warehouse_Name: string;
  storage_Name: string;
  storageOptions?: any[];
  original_Position: Number;
  new_StorageId: Number;
}

const productList: any = ref<ProductItem[]>([]);

// 仓库选项
const warehouseOptions = ref<any[]>([]);

// 控制弹窗显示
const showProductDialog = ref(false);

// 查询商品表单
const searchForm = ref({
  product_Number: "",
  product_Name: "",
});

// 商品数据（实际应从接口获取）
const productOptions = ref([]);

// 获取仓库列表
function fetchWarehouseOptions() {
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetWarehouseModel",
    method: "get",
  }).then((res) => {
    if (res.data.code === 200) {
      warehouseOptions.value = res.data.data || [];
    }
  });
}

// 根据仓库ID获取库位列表
function fetchStorageOptions(warehouseId: number, rowIndex: number) {
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetStorageModel",
    method: "get",
    params: {
      warehouse_ID: warehouseId,
    },
  }).then((res) => {
    if (res.data.code === 200) {
      productList.value[rowIndex].storageOptions = res.data.data || [];
    }
  });
}

// 处理仓库选择变化
function handleWarehouseChange(warehouseId: number, rowIndex: number) {
  // 清空库位选择
  productList.value[rowIndex].newstorageid = null;
  productList.value[rowIndex].storageOptions = [];

  if (warehouseId) {
    fetchStorageOptions(warehouseId, rowIndex);
  }
}



// 获取商品列表
function fetchProductOptions() {
  showProductDialog.value = true;
  StorageRed({
    url: "/api/Reporting_losses/GetProductByWarehouse_InOrOut",
    method: "get",
    params: {
      product_Number: searchForm.value.product_Number,
      product_Name: searchForm.value.product_Name,
      pageindex: pageQuery1.pageindex,
      pagesize: pageQuery1.pagesize,
    },
  }).then((res) => {
    productOptions.value = res.data.data;
    pageQuery1.totalCount = res.data.totalCount;
    pageQuery1.totalPage = res.data.totalPage;
  });
}

// 选中的商品
const selectedProducts = ref<ProductItem[]>([]);

// 修改 handleSelectionChange，确保深拷贝
function handleSelectionChange(val: ProductItem[]) {
  selectedProducts.value = val.map((item) => ({ ...item })); // 深拷贝
}

// 批量添加到移库产品表格
function onSelectProducts() {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning("请先选择要添加的产品");
    return;
  }

  
  // 生成统一批次号
  const batchCode = generateBatchCode();

    // 添加所有选中的产品到表格（不进行重复过滤）
    productList.value.push(
    ...selectedProducts.value.map((row) => {
      console.log("处理商品行数据:", row);
      return {
        id: row.id,
        productCode: row.product_Number,
        productName: row.product_Name,
        specifications: row.specifications,
        price: Number(row.price) || 0,
        product_Id: row.product_Id,
        category_Name: row.category_Name,
        newLocation: "",
        batch: batchCode, // 统一批次号
        allotCount: "",
        original_Warehouse: row.warehouse_ID,
        original_StorageId: row.storage_ID,
        currentLocation: row.warehouse_Name + ":" + row.storage_Name,
        original_Position: "",
        new_StorageId: "",
      };
    })
  );

  ElMessage.success(`成功添加${selectedProducts.value.length}个产品`);

  // 重置状态
  showProductDialog.value = false;
  selectedProducts.value = [];
}

onMounted(() => {
  form.movingCode = generateMoveStorageCode();
  fetchWarehouseOptions(); // 获取仓库列表
});

//生成移库单号
function generateMoveStorageCode() {
  const now = new Date();
  const pad = (n: any) => n.toString().padStart(2, "0");
  return (
    "YK" +
    now.getFullYear() +
    pad(now.getMonth() + 1) +
    pad(now.getDate()) +
    pad(now.getHours()) +
    pad(now.getMinutes()) +
    pad(now.getSeconds())
  );
}

const pageQuery1: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});

// 删除产品行
function removeProduct(index: any) {
  productList.value.splice(index, 1);
}

// 提交移库单
function onSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) {
      ElMessage.error("请完善必填项！");
      return;
    }

    if (productList.value.length === 0) {
      ElMessage.error("请至少添加一个产品！");
      return;
    }

    // 验证是否选择了移入库位
    const invalidRows = productList.value.filter(
      (row: any) => !row.original_Position || !row.new_StorageId
    );
    if (invalidRows.length > 0) {
      ElMessage.error("请为所有产品选择移入库位！");
      return;
    }

    // 生成统一批次号
    const batchCode = generateBatchCode();
    productList.value.forEach((row: any) => {
      row.batch = batchCode;
    });

    // 1. 遍历产品列表，合并表单信息
    const items = productList.value.map((row: any) => {
      console.log("提交时的行数据:", row);
      return {
        ...form, // 上部分表单信息
        // 下部分产品信息，覆盖或补充form中的同名字段
        warehouse_InOrOutId: row.id,
        product_Id: row.product_Id,
        product_Number: row.productCode,
        product_Name: row.productName,
        specifications: row.specifications,
        price: Number(row.price) || 0,
        batch: row.batch,
        allotCount: Number(row.allotCount) || 0,
        original_Warehouse: row.original_Warehouse,
        original_StorageId: row.original_Warehouse,
        original_Position: row.original_Position,
        new_StorageId: row.new_StorageId,
        // 确保制单人和制单时间正确传递
        createUse: form.createUse, // 用户ID
        createTime: form.createTime, // 制单时间
        tableType: 1,
      };
    });

    // 2. 组装参数对象
    const params = { items };

    // 3. 调用接口
    StorageWrite({
      url: "/api/AllotMoving_Inventory/CreateAllotMoving_Inventory",
      method: "post",
      data: params,
    }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        router.push("/MoveStorageView");
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
}

function onCancel() {
  router.back();
}

watch(pageQuery1, () => {
  fetchProductOptions();
});

//生成批次号
function generateBatchCode() {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < 5; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 表单ref
const formRef = ref<FormInstance>();

// 校验规则
const rules: FormRules = {
  allotWarehouseType: [
    { required: true, message: "移库单类型不能为空", trigger: "change" },
  ],
};
</script>

<style scoped>
.add-move-storage {
  padding: 20px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.form-title {
  font-size: 16px;
  font-weight: bold;
}

.required-tip {
  font-size: 12px;
  color: #999;
}
</style>
